//
//  BrandCustom.m
//  cutter
//
//  Created by mac on 16/1/20.
//  Copyright © 2016年 e360. All rights reserved.
//

#import "AppData+Product.h"

@implementation AppData (Product)
+(id)findChild:(id)item items:(id)items name:(NSString*)name{
    NSInteger iid = 0;
    if (item != nil) {
        iid = [[item objectForKey:@"id"] integerValue];
    }
    if ([items isKindOfClass:NSDictionary.class]) {
        items = [items allValues];
    }
    //
    NSMutableArray *parent = [NSMutableArray array];
    for (id tmp in items) {
        if (iid == [[tmp objectForKey:@"parentid"] integerValue]) {
            NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary:tmp];
            [data setValue:[self findChild:tmp items:items name:name] forKey:@"child"];
            [data setValue:[tmp objectForKey:name] forKey:@"name"];
            [parent addObject:data];
        }
    }
    if ([parent count] > 0) {
        NSMutableDictionary *all = [NSMutableDictionary dictionary];
        [all setValue:[NSString stringWithFormat:@"所有产品"] forKey:@"name"];
        [all setValue:[NSNumber numberWithBool:YES] forKey:@"all"];
        [all setValue:[item objectForKey:@"id"] forKey:@"id"];
        [parent insertObject:all atIndex:0];
        return parent;
    }
    return nil;
}
+(id)valueWithSql:(NSString*)sql field:(NSString*)field{
    NSArray *data = [[TMSQLite shareInstance] query:sql];
    if (data) {
        NSMutableArray *temp = [NSMutableArray array];
        for (id item in data) {
            id value = [item objectForKey:field];
            if (value && value != [NSNull null]) {
                [temp addObject:value];
            }
        }
        return temp;
    }
    return nil;
}
//
+(id)productClassify{
    if ([[UIDevice currentDevice] network] != UIDeviceNetworkNone) {
        static CGFloat time = 0;
        CGFloat curr = [[NSDate date] timeIntervalSince1970];
        if (curr - time > 1) {
            time = curr;
            //
            NSArray *items = [[self loadJson:@"?n=api&a=product&c=product_cate" key:@"data" data:nil] allValues];
            if (items) {
                [[[TMSQLite shareInstance] transaction] begin];
                [[TMSQLite shareInstance] query:@"DELETE FROM e360_product_cate"];
                for (id item in items) {
                    NSString *sql = [self fromInsert:@"e360_product_cate" data:item];
                    [[TMSQLite shareInstance] query:sql];
                }
                [[[TMSQLite shareInstance] transaction] commit];
            }
        }
    }
    //本地查询
    NSString *sql = @"SELECT *, catename AS name FROM e360_product_cate WHERE deleted=0 ORDER BY sort ASC";
    NSMutableArray *items = [[TMSQLite shareInstance] query:sql];
    NSMutableArray *child = [self findChild:nil items:items name:@"catename"];
    //
    NSMutableDictionary *temp = [NSMutableDictionary dictionary];
    [temp setValue:@"品类" forKey:@"name"];
    [temp setValue:child forKey:@"child"];
    return temp;
}
+(id)productScreen{
    if ([[UIDevice currentDevice] network] != UIDeviceNetworkNone) {
        static CGFloat time = 0;
        CGFloat curr = [[NSDate date] timeIntervalSince1970];
        if (curr - time > 1) {
            time = curr;
            //
            NSArray *style = [self loadJson:@"?n=api&a=product&c=product&m=style" key:@"data" data:nil];
            NSArray *space = [self loadJson:@"?n=api&a=product&c=product&m=space" key:@"data" data:nil];
            NSArray *color = [self loadJson:@"?n=api&a=product&c=product&m=color" key:@"colors" data:nil];
            NSArray *processing = [self loadJson:@"?n=api&a=product&c=product&m=processing" key:@"data" data:nil];
            //插入数据
            if(style || space || color || processing){
                [[[TMSQLite shareInstance] transaction] begin];
                [[TMSQLite shareInstance] query:@"DELETE FROM e360_product_style"];
                [[TMSQLite shareInstance] query:@"DELETE FROM e360_product_space"];
                [[TMSQLite shareInstance] query:@"DELETE FROM e360_product_color"];
                [[TMSQLite shareInstance] query:@"DELETE FROM e360_product_processing"];
                //
                for (id item in style) {
                    NSString *sql = [self fromInsert:@"e360_product_style" data:item];
                    [[TMSQLite shareInstance] query:sql];
                }
                for (id item in space) {
                    NSString *sql = [self fromInsert:@"e360_product_space" data:item];
                    [[TMSQLite shareInstance] query:sql];
                }
                for (id item in color) {
                    NSString *sql = [self fromInsert:@"e360_product_color" data:item];
                    [[TMSQLite shareInstance] query:sql];
                }
                for (id item in processing) {
                    NSString *sql = [self fromInsert:@"e360_product_processing" data:item];
                    [[TMSQLite shareInstance] query:sql];
                }
                [[[TMSQLite shareInstance] transaction] commit];
            }
        }
    }
    //
    NSArray *data = [[TMSQLite shareInstance] query:@"SELECT * FROM e360_product_style WHERE deleted=0"];
    NSMutableDictionary *style = [NSMutableDictionary dictionary];
    [style setValue:[self findChild:nil items:data name:@"stylename"] forKey:@"child"];
    [style setValue:[NSNumber numberWithInt:0] forKey:@"id"];
    [style setValue:@"风格" forKey:@"name"];
    id aid = [style objectForKey:@"id"];
    for (id chid in [style objectForKey:@"child"]) {
        [chid setValue:aid forKey:@"parentid"];
    }
    //
    data = [[TMSQLite shareInstance] query:@"SELECT * FROM e360_product_space WHERE deleted=0"];
    NSMutableDictionary *space = [NSMutableDictionary dictionary];
    [space setValue:[self findChild:nil items:data name:@"spacename"] forKey:@"child"];
    [space setValue:[NSNumber numberWithInt:1] forKey:@"id"];
    [space setValue:@"空间" forKey:@"name"];
    id bid = [space objectForKey:@"id"];
    for (id chid in [space objectForKey:@"child"]) {
        [chid setValue:bid forKey:@"parentid"];
    }
    //
    data = [[TMSQLite shareInstance] query:@"SELECT * FROM e360_product_processing WHERE deleted=0"];
    NSMutableDictionary *processing = [NSMutableDictionary dictionary];
    [processing setValue:[self findChild:nil items:data name:@"processingname"] forKey:@"child"];
    [processing setValue:[NSNumber numberWithInt:2] forKey:@"id"];
    [processing setValue:@"工艺" forKey:@"name"];
    id cid = [processing objectForKey:@"id"];
    for (id chid in [processing objectForKey:@"child"]) {
        [chid setValue:cid forKey:@"parentid"];
    }
    //
    data = [[TMSQLite shareInstance] query:@"SELECT * FROM e360_product_color WHERE deleted=0"];
    NSMutableDictionary *color = [NSMutableDictionary dictionary];
    [color setValue:[self findChild:nil items:data name:@"colorname"] forKey:@"child"];
    [color setValue:[NSNumber numberWithInt:3] forKey:@"id"];
    [color setValue:@"颜色" forKey:@"name"];
    id did = [color objectForKey:@"id"];
    for (id chid in [color objectForKey:@"child"]) {
        [chid setValue:did forKey:@"parentid"];
    }
    //
    NSMutableDictionary *temp = [NSMutableDictionary dictionary];
    [temp setValue:[NSMutableArray arrayWithObjects:style, space, processing, color, nil] forKey:@"child"];
    [temp setValue:@"筛选" forKey:@"name"];
    return temp;
}
+(id)productList:(NSDictionary*)condition{
    if ([[UIDevice currentDevice] network] != UIDeviceNetworkNone) {
        NSMutableString *request = [NSMutableString stringWithString:@"?n=api&a=product&c=product&m=index"];
        for (id key in condition) {
            id val = [condition objectForKey:key];
            if (val && val != [NSNull null]) {
                [request appendFormat:@"&%@=%@", key, val];
            }else{
                [request appendFormat:@"&%@=", key];
            }
        }
        NSArray *items = [self loadJson:request key:@"products" data:nil];
        if(items){
            [[[TMSQLite shareInstance] transaction] begin];
            for (id item in items) {
                id subproduct = [item objectForKey:@"product_model_material_match_subproduct"];
                if (isEmpty(subproduct) == NO) {
                    for (id item in subproduct) {
                        NSString *sql = [self fromInsert:@"product_model_material_match_subproduct" data:item];
                        [[TMSQLite shareInstance] query:sql];
                    }
                }
                //
                id material = [item objectForKey:@"product_model_material"];
                if (isEmpty(material) == NO) {
                    for (id item in material) {
                        NSString *sql = [self fromInsert:@"product_model_material" data:item];
                        [[TMSQLite shareInstance] query:sql];
                    }
                }
                //
                NSString *sql = [self fromInsert:@"e360_product" data:item];
                [[TMSQLite shareInstance] query:sql];
            }
            [[[TMSQLite shareInstance] transaction] commit];
        }
    }
    //本地查询
    NSString *sql = nil;
    if ([condition objectForKey:@"productid"]) {
        sql = [NSString stringWithFormat:@"SELECT * FROM e360_product WHERE id IN (%@)", [condition objectForKey:@"productid"]];
    }else{
        sql = @"SELECT * FROM e360_product WHERE IFNULL(pic_jpg,'')!='' AND deleted=0 AND temp_hardpacked=0 AND status=1 AND subproductid!=0";
        if ([condition objectForKey:@"cateid"]) {
            NSArray *cate = [[TMSQLite shareInstance] query:@"SELECT * FROM e360_product_cate"];
            NSArray *cids = [self getAllChildId:cate parentid:[condition objectForKey:@"cateid"]];
            if (cids) {
                sql = [sql stringByAppendingFormat:@" AND cateid IN (%@)", [cids componentsJoinedByString:@","]];
            }
        }
        if ([condition objectForKey:@"styleid"]) {
            sql = [sql stringByAppendingFormat:@" AND (','||styleid||',') LIKE '%%,%@,%%'", [condition objectForKey:@"styleid"]];
        }
        if ([condition objectForKey:@"spaceid"]) {
            sql = [sql stringByAppendingFormat:@" AND (','||spaceid||',') LIKE '%%,%@,%%'", [condition objectForKey:@"spaceid"]];
        }
        if ([condition objectForKey:@"processingid"]) {
            sql = [sql stringByAppendingFormat:@" AND (','||processingid||',') LIKE '%%,%@,%%'", [condition objectForKey:@"processingid"]];
        }
        if ([condition objectForKey:@"colorid"]) {
            NSString *color = [NSString stringWithFormat:@"SELECT a.id FROM e360_product_model_material_match_subproduct a ,e360_product_model_material b, e360_product_material c WHERE a.match_id=b.match_id AND b.material_id=c.id AND ','||c.colorid||',' LIKE '%%,%@,%%'", [condition objectForKey:@"colorid"]];
            sql = [sql stringByAppendingFormat:@" AND subproductid IN (%@)", color];
        }
        if ([condition objectForKey:@"producingareaid"]) {
            sql = [sql stringByAppendingFormat:@" AND producingareaid=%@", [condition objectForKey:@"producingareaid"]];
        }
        if ([condition objectForKey:@"assembled"]) {
            sql = [sql stringByAppendingFormat:@" AND assembled=%@", [condition objectForKey:@"assembled"]];
        }
        if ([condition objectForKey:@"clientid"]) {
            sql = [sql stringByAppendingFormat:@" AND clientid=%@", [condition objectForKey:@"clientid"]];
        }
        if ([condition objectForKey:@"price"]) {
            id price = [condition objectForKey:@"price"];
            NSArray *temp = [price componentsSeparatedByString:@"-"];
            if (temp.count==2) {
                sql = [sql stringByAppendingFormat:@" AND saleprice>=%@ AND saleprice<=%@", [temp firstObject], [temp lastObject]];
            }
        }
        if ([condition objectForKey:@"keyword"]) {
            id keyword = [condition objectForKey:@"keyword"];
            sql = [sql stringByAppendingFormat:@" AND (productname like '%%%@%%' OR productsn like '%%%@%%')", keyword, keyword];
        }
        if ([condition objectForKey:@"sort"]) {
            NSArray *sort = [[condition objectForKey:@"sort"] componentsSeparatedByString:@"|"];
            if (sort.count == 2) {
                sql = [sql stringByAppendingFormat:@" ORDER BY %@ %@", [sort firstObject], [sort lastObject]];
            }else{
                sql = [sql stringByAppendingString:@" ORDER BY id ASC"];
            }
        }else{
            sql = [sql stringByAppendingString:@" ORDER BY id ASC"];
        }
        if ([condition objectForKey:@"page"] && [condition objectForKey:@"limit"]) {
            int page = [[condition objectForKey:@"page"] intValue] - 1;
            int limit = [[condition objectForKey:@"limit"] intValue];
            sql = [sql stringByAppendingFormat:@" LIMIT %d, %d", page * limit, limit];
        }
    }
    return [[TMSQLite shareInstance] query:sql];
}
+(id)productDetail:(id)pid{
    if (pid) {
        if ([[UIDevice currentDevice] network] != UIDeviceNetworkNone) {
            NSMutableArray *items = [NSMutableArray array];
            NSString *request = [NSString stringWithFormat:@"?n=api&a=product&c=product&m=info&id=%@", pid];
            id temp = [self loadJson:request key:@"product" data:nil];
            if (temp) {
                if ([temp isKindOfClass:NSArray.class]) {
                    [items addObjectsFromArray:temp];
                }else{
                    [items addObject:temp];
                }
            }
            if ([items count] > 0) {
                [[[TMSQLite shareInstance] transaction] begin];
                for (id item in items) {
                    [item setValue:[item objectForKey:@"image"] forKey:@"pic"];
                    NSString *sql = [self fromInsert:@"e360_product" data:item];
                    [[TMSQLite shareInstance] query:sql];
                    //
                    NSArray *options = [[item objectForKey:@"realation_table"] objectForKey:@"product_attribute_option"];
                    if (isEmpty(options) == NO) {
                        for (id option in options) {
                            sql = [self fromInsert:@"e360_product_attribute_option" data:option];
                            [[TMSQLite shareInstance] query:sql];
                        }
                    }
                    //
                    NSArray *attributes = [[item objectForKey:@"realation_table"] objectForKey:@"product_attribute"];
                    if (isEmpty(attributes) == NO) {
                        for (id attribute in attributes) {
                            sql = [self fromInsert:@"e360_product_attribute" data:attribute];
                            [[TMSQLite shareInstance] query:sql];
                        }
                    }
                    //
                    NSArray *metas = [[item objectForKey:@"realation_table"] objectForKey:@"product_meta"];
                    if (isEmpty(metas) == NO) {
                        for (id meta in metas) {
                            sql = [self fromInsert:@"e360_product_meta" data:meta];
                            [[TMSQLite shareInstance] query:sql];
                        }
                    }
                    //
                    NSArray *views = [[item objectForKey:@"realation_table"] objectForKey:@"product_pic"];
                    if (isEmpty(views) == NO) {
                        for (id view in views) {
                            sql = [self fromInsert:@"e360_product_pic" data:view];
                            [[TMSQLite shareInstance] query:sql];
                        }
                    }
                    //
                    NSDictionary *info = [item objectForKey:@"model_info"];
                    if (isEmpty(info) == NO) {
                        NSDictionary *model = [info objectForKey:@"model"];
                        if (isEmpty(model) == NO) {
                            sql = [self fromInsert:@"e360_product_model" data:model];
                            [[TMSQLite shareInstance] query:sql];
                            //
                            NSDictionary *match = [model objectForKey:@"match"];
                            if (isEmpty(match) == NO) {
                                sql = [self fromInsert:@"e360_product_model_material_match" data:match];
                                [[TMSQLite shareInstance] query:sql];
                            }
                            //
                            NSArray *materials = [model objectForKey:@"material"];
                            if (isEmpty(materials) == NO) {
                                for (id material in materials) {
                                    sql = [self fromInsert:@"e360_product_material" data:material];
                                    [[TMSQLite shareInstance] query:sql];
                                    //
                                    NSDictionary *color = [material objectForKey:@"color"];
                                    if (isEmpty(color) == NO) {
                                        sql = [self fromInsert:@"e360_product_color" data:color];
                                        [[TMSQLite shareInstance] query:sql];
                                    }
                                    //
                                    NSDictionary *modelMaterial = [material objectForKey:@"product_model_material"];
                                    if (isEmpty(modelMaterial) == NO) {
                                        sql = [self fromInsert:@"e360_product_model_material" data:modelMaterial];
                                        [[TMSQLite shareInstance] query:sql];
                                    }
                                }
                            }
                            //
                            NSArray *materialClasss = [model objectForKey:@"material_class"];
                            if (isEmpty(materialClasss) == NO) {
                                for (id materialClass in materialClasss) {
                                    sql = [self fromInsert:@"e360_product_model_material_class" data:materialClass];
                                    [[TMSQLite shareInstance] query:sql];
                                }
                            }
                        }
                        //
                        NSDictionary *product = [info objectForKey:@"product"];
                        if (isEmpty(product) == NO) {
                            sql = [self fromInsert:@"e360_product_model_material_match_subproduct" data:product];
                            [[TMSQLite shareInstance] query:sql];
                        }
                    }
                }
                [[[TMSQLite shareInstance] transaction] commit];
            }
        }
        //
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM e360_product WHERE id IN (%@)", pid];
        return [[TMSQLite shareInstance] query:sql];
    }
    return nil;
}
+(id)productAttribute:(id)temp all:(BOOL)all{
    if (isEmpty([temp objectForKey:@"subproductid"])==NO) {
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM e360_product_model_material_match_subproduct WHERE deleted=0 AND id=%@",[temp objectForKey:@"subproductid"]];
        NSMutableDictionary *info = [[[TMSQLite shareInstance] query:sql] firstObject];
        if (info) {
            sql = [NSString stringWithFormat:@"SELECT b.* FROM e360_product_model_material_match a,e360_product_model b WHERE a.deleted=0 AND b.deleted=0 AND a.model_id=b.id AND a.id=%@",[info objectForKey:@"match_id"]];
            NSMutableDictionary *model = [[[TMSQLite shareInstance] query:sql] firstObject];
            if (model) {
                sql = [NSString stringWithFormat:@"SELECT a.* FROM e360_product_material a, e360_product_model_material b, e360_product_model_material_class c,e360_product_model_material_match d WHERE a.deleted=0 AND b.deleted=0 AND c.deleted=0 AND b.material_id=a.id  AND d.id=b.match_id AND c.id=b.class_id AND c.model_id=d.model_id AND d.model_id=%@", [model objectForKey:@"id"]];
                NSArray *materials = [[TMSQLite shareInstance] query:sql];
                if (materials) {
                    [model setValue:materials forKey:@"material"];
                    //
                    for (id material in materials) {
                        sql = [NSString stringWithFormat:@"SELECT * FROM e360_product_color WHERE deleted=0 AND id IN (%@)",[material objectForKey:@"colorid"]];
                        NSDictionary *color = [[[TMSQLite shareInstance] query:sql] firstObject];
                        if (color) {
                            [material setValue:color forKey:@"color"];
                            [material setValue:[color objectForKey:@"colorname"] forKey:@"colorname"];
                        }
                    }
                }
                [info setValue:model forKey:@"model"];
            }
            [temp setValue:info forKey:@"model_info"];
        }
    }
    if (all == YES) {
        uint index = MIN([[temp objectForKey:@"installation"] intValue], 4);
        NSArray *install = [NSArray arrayWithObjects:@"", @"不需要安装", @"自行安装", @"供应商安装", @"外协安装", nil];
        [temp setValue:[NSArray arrayWithObject:[install objectAtIndex:index]] forKey:@"installationname"];
        //
        if (isEmpty([temp objectForKey:@"cateid"])==NO) {
            NSString *sql = [NSString stringWithFormat:@"SELECT catename FROM e360_product_cate WHERE deleted=0 AND id=%@", [temp objectForKey:@"cateid"]];
            [temp setValue:[self valueWithSql:sql field:@"catename"] forKey:@"catename"];
        }
        if (isEmpty([temp objectForKey:@"styleid"])==NO) {
            NSString *sql = [NSString stringWithFormat:@"SELECT stylename FROM e360_product_style WHERE deleted=0 AND id IN (%@)", [temp objectForKey:@"styleid"]];
            [temp setValue:[self valueWithSql:sql field:@"stylename"] forKey:@"stylename"];
        }
        if (isEmpty([temp objectForKey:@"spaceid"])==NO) {
            NSString *sql = [NSString stringWithFormat:@"SELECT spacename FROM e360_product_space WHERE deleted=0 AND id IN (%@)", [temp objectForKey:@"spaceid"]];
            [temp setValue:[self valueWithSql:sql field:@"spacename"] forKey:@"spacename"];
        }
        if (isEmpty([temp objectForKey:@"processingid"])==NO) {
            NSString *sql = [NSString stringWithFormat:@"SELECT processingname FROM e360_product_processing WHERE deleted=0 AND id IN (%@)", [temp objectForKey:@"processingid"]];
            [temp setValue:[self valueWithSql:sql field:@"processingname"] forKey:@"processingname"];
        }
        if (isEmpty([temp objectForKey:@"id"])==NO) {
            NSString *sql = [NSString stringWithFormat:@"SELECT * FROM e360_product_pic WHERE deleted=0 AND productid=%@", [temp objectForKey:@"id"]];
            //
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setValue:[temp objectForKey:@"pic_jpg"] forKey:@"pic_jpg"];
            [dic setValue:[temp objectForKey:@"thumb600"] forKey:@"thumb600"];
            [dic setValue:[temp objectForKey:@"thumb400_jpg"] forKey:@"thumb400_jpg"];
            //
            NSMutableArray *images = [NSMutableArray arrayWithObject:dic];
            [images addObjectsFromArray:[[TMSQLite shareInstance] query:sql]];
            [temp setValue:images forKey:@"images"];
        }
        //动态属性
        NSString *sql = [NSString stringWithFormat:@"SELECT a.attrname name, b.attributeoption option FROM e360_product_attribute a,e360_product_meta b WHERE a.deleted=0 AND b.deleted=0 AND a.id=b.attributeid AND b.productid=%@",[temp objectForKey:@"id"]];
        NSArray *attributes = [[TMSQLite shareInstance] query:sql];
        if (attributes) {
            for (id attribute in attributes) {
                sql = [NSString stringWithFormat:@"SELECT content FROM e360_product_attribute_option WHERE deleted=0 AND id IN (%@)",[attribute objectForKey:@"option"]];
                [attribute setValue:[self valueWithSql:sql field:@"content"] forKey:@"option"];
            }
            [temp setValue:attributes forKey:@"attributes"];
        }
    }
    return temp;
}
@end